package zheezes.swt.util;

import org.apache.commons.beanutils.PropertyUtils;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerSorter;

public class FieldViewerSorter extends ViewerSorter {
	private String name = null;
	private boolean asc = true;

	public int compare(Viewer viewer, Object m, Object n) {
		int diff = 0;	
		if (name == null) {
			return 0;
		}
		Class clazz = m.getClass();
		if (clazz.equals(n.getClass())) {
			Object mv = null;
			Object nv = null;
			try {
				mv = PropertyUtils.getProperty(m, name);
				nv = PropertyUtils.getProperty(n, name);
			} catch (Exception e) {
				return 0;
			}
			if (mv == null) {
				if (nv == null) {
					diff = 0;
				} else {
					diff = -1;
				}
			} else {
				if (nv == null) {
					diff = 1;
				} else {
					if (mv instanceof Comparable) {
						Comparable cmv = (Comparable) mv;
						diff = cmv.compareTo(nv);
					} else {
						diff = mv.toString().compareTo(nv.toString());
					}
				}
			}
		}
		if (!asc) {
			diff = -diff;
		}
		return diff;
	}

	public void setName(String name) {
		this.name = name;
	}

	public void setAsc(boolean asc) {
		this.asc = asc;
	}
}
